// @Name    : merchant_driver
// @author  : simon
// @date    : 2020/10/31 09:20
// @desc : 事件总线
// 增加移除监听

import 'dart:async';
import 'package:event_bus/event_bus.dart';

class CaiNetworkNotificationCenter {
  static final CaiNetworkNotificationCenter _manager = CaiNetworkNotificationCenter();
  static CaiNetworkNotificationCenter get defaultCenter => _manager;

  // static final ZXNSNotificationCenter _instance =
  // ZXNSNotificationCenter._internal();
  // factory ZXNSNotificationCenter() => _instance;
  // ZXNSNotificationCenter._internal();

  final Map<String, StreamSubscription> _streamsMap = {};

  EventBus get eventBus {
    return _eventBus;
  }

  final EventBus _eventBus = EventBus();

  //任何Dart类都可以用作事件。
  void postNotification(event) {
    _eventBus.fire(event);
  }

  //接收通知
  Stream<T> on<T>() {
    return _eventBus.on();
  }

  //添加指定通知并添加管理监听
  StreamSubscription addObserverNotification<T>(
      String name, Function(T event)? onData) {
    StreamSubscription subscription =
    _manager.on<CaiNetworkNotification>().listen((event) {
      if (onData != null) {
        if (event.name == name) {
          onData(event as T);
        }
      }
    });
    _streamsMap[name] = subscription;
    return subscription;
  }

  //移除监听
  void removeObserverNotification(String name) {
    if (_streamsMap.keys.contains(name)) {
      StreamSubscription? subscription = _streamsMap[name];
      if (subscription != null) {
        subscription.cancel();
        _streamsMap.remove(name);
      }
    }
  }
}

class CaiNetworkNotification {
  final String? name;
  final dynamic object;

  const CaiNetworkNotification({required this.name, this.object});
}
/*
例如：
    CaiNetworkNotificationCenter.defaultCenter.postNotification(ZXNetworkNotification(name:NotificationName.tabSelectEvent,object: 1));

    CaiNetworkNotificationCenter.defaultCenter.addObserverNotification(ZXNotificationName.deliveryDetailBeginDelivery,(event) {
      setState(() {
        _selectIndex = event.object;
      });
    });
 */
